package com.halflife.comeElectricity.orderMng.order;

import com.halflife.framework.exception.BusinessException;
import com.halflife.comeElectricity.member.rider.Rider;
import com.halflife.comeElectricity.member.rider.RiderRepository;
import com.halflife.comeElectricity.util.Constants;
import com.halflife.message.OrderMessage;
import com.halflife.message.OrderMessageRepository;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.dao.DataAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by zhaoyf on 2018/2/12.
 */
@Service
public class OrderService {
    public static final Logger logger = LoggerFactory.getLogger(OrderService.class);
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderExtRepository orderExtRepository;
    @Resource
    private RiderRepository riderRepository;
    @Resource
    private OrderMessageRepository orderMessageRepository;


    public void add(Order order, OrderExt ext) {
        Integer id = orderRepository.insert(order);
        ext.setId(order.getId());
        orderExtRepository.insert(ext);
        template.opsForValue().set(Constants.watch+id,Constants.default_count);
        Order updateOrder = new Order();
        updateOrder.setId(order.getId());
//        updateOrder.setStatus(OrderEnum.NOPAY.m_orderStatus.byteValue());
        updateOrder.setStatus(OrderEnum.WAITTOGET.m_orderStatus.byteValue());
        orderRepository.updateByPrimaryKeySelective(updateOrder);
        template.opsForValue().set(Constants.watch+order.getId(),Constants.default_count);

    }
    @Value("${system.rider.max_items}")
    public Integer maxItems;
    @Value("${system.rider.max_distance}")
    public Integer maxDistance;

    public List<Order> list(Integer id, Integer longitude, Integer latitude, Integer limit, Integer page) {
        List list = null;
        if(longitude!=null&&latitude!=null){
        }
        return list;
    }
    private synchronized void setWatch(Integer id) {
        template.opsForValue().set(Constants.watch+id,Constants.default_count);
    }
    private List<Order> findByGeo(Integer longitude,Integer latitude){
        return null;
    }

    @Autowired
    private StringRedisTemplate template;
    public void grabOrder(Rider rider, Integer id){
        String count = template.opsForValue().get(Constants.watch+id);
        if(StringUtils.isEmpty(count)){
            this.setWatch(id);
            count = Constants.default_count;
            System.out.println("=====+++++"+count);
        }
        Integer val = Integer.valueOf(count);
        System.out.println("====="+count);
        if(val==1) {
            List<Object> txResults = template.execute(new SessionCallback<List<Object>>() {
                public List<Object> execute(RedisOperations operations) throws DataAccessException {
                    operations.watch(Constants.watch + id);
                    operations.multi();
                    operations.opsForValue().increment(Constants.watch + id, -1);
                    List list = operations.exec();

                    // This will contain the results of all ops in the transaction
                    return list;
                }
            });
            if (txResults !=null && txResults.size() > 0) {
                System.out.println("Number of items added to set: " + txResults.get(0));
                this.getOrder(rider, id);
            }else
                throw new BusinessException("订单已经被别的骑手抢走了！");
        }else{
            throw new BusinessException("订单已经被别的骑手抢走了！");
        }

    }
    public void getOrder(Rider rider, Integer id){
        rider = riderRepository.selectByPrimaryKey(rider.getId());
        Order updateOrder = new Order();
        updateOrder.setId(id);
        updateOrder.setRiderId(rider.getId());
        updateOrder.setRiderName(rider.getName());
        updateOrder.setRiderPhone(rider.getPhone());
        updateOrder.setStatus(OrderEnum.WAITGO.m_orderStatus.byteValue());

        OrderExt updateExt = new OrderExt();
        updateExt.setId(id);
        updateExt.setRideTime(new Date().getTime());

        Order order = orderRepository.selectByPrimaryKey(id);
        if(order.getStatus() != OrderEnum.WAITTOGET.m_orderStatus.byteValue()){
            throw new BusinessException("订单以及被别的骑手抢走了！");
        }
        template.delete(Constants.watch + id);
        orderExtRepository.updateByPrimaryKeySelective(updateExt);
        orderRepository.updateByPrimaryKeySelective(updateOrder);
        //插入通知
    }

    public String getLocation(Integer id){
        String location = (String)template.opsForHash().get("location",id);
        return location;
    }
}
